package com.afbx.common.convert.converters;

import com.afbx.common.convert.ConvertChain;
import com.afbx.common.convert.ConvertFailedException;
import com.afbx.common.convert.Converter;

/**
 * @author liangliang
 */
public class LongConverter implements Converter {
	protected static final Long DEFAULT_VALUE = new Long(0L);

	public Object convert(Object value, ConvertChain chain) {
		if (value == null) {
			throw new ConvertFailedException().setDefaultValue(DEFAULT_VALUE);
		}

		if (value instanceof Long) {
			return value;
		}

		if (value instanceof Number) {
			return new Long(((Number) value).longValue());
		}

		if (value instanceof String) {
			String strValue = ((String) value).trim();

			try {
				return Long.valueOf(strValue);
			} catch (NumberFormatException e) {
				if (strValue.length() > 0) {
					throw new ConvertFailedException(e).setDefaultValue(DEFAULT_VALUE);
				}

				throw new ConvertFailedException().setDefaultValue(DEFAULT_VALUE);
			}
		}

		return chain.convert(value);
	}
}
